//
//  DuanDianURLViewController.m
//  LianXi7.11
//
//  Created by apple on 2017/7/11.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "DuanDianURLViewController.h"

@interface DuanDianURLViewController ()<NSURLSessionDownloadDelegate>
@property (nonatomic, copy) NSString *hehe;

@property (nonatomic, strong) UIProgressView *progress;
@property (nonatomic, strong) UILabel *progressLabel;

@property (nonatomic, strong) UIButton *btn;

@property (nonatomic, strong) NSData *reumeData;

@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@end

@implementation DuanDianURLViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    self.view.backgroundColor = [UIColor whiteColor];

    
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(30, 100, 200, 10)];
    
    self.progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 70, 100, 20)];
    
    self.progressLabel.textColor = [UIColor blueColor];
    
    [self.view addSubview:_progressLabel];
    
    [self.view addSubview:_progress];
    
    self.btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 400, 50, 50)];
    self.btn.backgroundColor = [UIColor blueColor];
    [self.btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];
 
    [self createBtnBack];
    
}

- (void)createBtnBack{
    
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(30, 440, 50, 50)];
    
    [btnBack setTitle:@"BACK" forState:UIControlStateNormal];
    [btnBack setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    btnBack.backgroundColor = [UIColor greenColor];
    
    [btnBack addTarget:self action:@selector(btnBack) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btnBack];
    
}

- (void)btnBack{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)xiaZai{

     NSString *str = @"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg";
    
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.task = [self.session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.task resume];
}

- (void)btnClick:(UIButton *)sender{

    // 按钮状态取反
    sender.selected = !sender.isSelected;
    
    if (nil == self.task) { // [开始下载/继续下载]
        if (self.reumeData) { // [继续下载]
            // 传入上次暂停下载返回的数据，就可以恢复下载
            self.task = [self.session downloadTaskWithResumeData:_reumeData];
            
            // 开始任务
            [self.task resume];
            
            self.reumeData = nil;
        }else{ // [开始下载]：从0开始下载
            
            [self xiaZai];
        }
        
    }else{ // [暂停下载]
        __weak typeof(self) weakSelf = self;
        [self.task cancelByProducingResumeData:^(NSData *resumeData) {
            // resumeData：包含了继续下载的位置\下载的路径
            weakSelf.reumeData = resumeData;
            weakSelf.task = nil;
        }];
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSString *dou = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    
    NSString *newPath = [dou stringByAppendingPathComponent:@"qq.dmg"];
    
    self.hehe = newPath;
    
    NSLog(@"--= %@",newPath);
    
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:newPath error:nil];
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    //1.0 和 100.0 都得放在前面，不然不显示。。。。。为啥嘞！
    self.progress.progress = 1.0 *totalBytesWritten/totalBytesExpectedToWrite;
    
    self.progressLabel.text = [NSString stringWithFormat:@" %.2f%%",100.0 *totalBytesWritten/totalBytesExpectedToWrite];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
